package pl.polsl.pum2.pj;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.WindowManager;

public class RubikActivity extends Activity {

  private GLSurfaceView        view;
  private OpenGLRenderer       renderer;
  private int                  cubeSize;

  private static RubikActivity rubikActivity = null;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    rubikActivity = this;

    int size = cubeSize = getIntent().getIntExtra("rubik-size", 3);
    int shuffles = 0;
    if (getIntent().getBooleanExtra("rubik-shuffle", true)) {
      shuffles = size * size;
    }
    
    float sensivity = getIntent().getFloatExtra("sensitivity", 0.0003f);

    DisplayMetrics displayMetrics = new DisplayMetrics();
    ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(displayMetrics);

    view = new GLSurfaceView(this);
    view.setEGLConfigChooser(8, 8, 8, 8, 16, 0); // Set pixelformat
    view.setRenderer(renderer = new OpenGLRenderer(size, shuffles, displayMetrics, sensivity));

    
    // Use a surface format with an Alpha channel:
    view.getHolder().setFormat(PixelFormat.TRANSLUCENT);

    setContentView(view);
  }

  @Override
  protected void onResume() {
    super.onResume();
    view.onResume();
  }

  @Override
  protected void onPause() {
    super.onPause();
    view.onPause();
  }

  @Override
  public boolean onTouchEvent(MotionEvent event) {
    Point click = new Point((int) event.getX(), (int) event.getY());

    switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
        renderer.startDrag(click);
        break;
      case MotionEvent.ACTION_MOVE:
        renderer.drag(click);
        break;
      case MotionEvent.ACTION_UP:
        renderer.endDrag(click);
        break;
    }
    return true;
  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent msg) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
      Intent intent = new Intent();
      intent.setClass(RubikActivity.this, PauseActivity.class);
      startActivity(intent);
      return true; // <- Will 'override' default behaviour
    }
    return super.onKeyDown(keyCode, msg);
  }

  public void cubeSolved() {
    Intent intent = new Intent();
    intent.setClass(RubikActivity.this, SolvedActivity.class);
    startActivity(intent);
  }

  public static RubikActivity getInstance() {
    return rubikActivity;
  }

  public int getCubeSize() {
    return cubeSize;
  }
}
